package com.ruoyi.app.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.upload.QiniuUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.CustomId;
import com.ruoyi.system.domain.wx.WxUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.wx.IWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 微信用户api
 *
 * @author mix
 * @date 2023-08-07
 */
@RestController
@RequestMapping("/wx/user")

public class WxUserAPI {

    @Autowired
    private IWxUserService wxUserService;
    @Autowired
    private ISysConfigService configService;

    @Value("${wx.login}")
    private String url;
    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;

    @GetMapping("/login")
    public AjaxResult login(String wxCode) {
        String apiUrl = StrUtil.format(
                url, appId, secret, wxCode);
        String body = HttpRequest.get(apiUrl).execute().body();
        JSONObject json = JSON.parseObject(body);
        String sessionKey = json.get("session_key").toString();
        String openId = json.get("openid").toString();

        // 登录成功
        if (StrUtil.isNotBlank(openId)) {
            // 通过 openId 获取用户
            WxUser wxUser = wxUserService.selectWxUserByOpenId(openId);

            if (wxUser != null) {
                // 保存新的 sessionId
                wxUser.setSessionKey(sessionKey);
                wxUser.setModifyTime(new Date());
                wxUser.setUserLasttime(new Date());
                wxUserService.updateWxUser(wxUser);

            } else {
                // 新增用户
                wxUser = new WxUser();
                wxUser.setSessionKey(sessionKey);
                wxUser.setModifyTime(new Date());
                wxUser.setUserLasttime(new Date());
                wxUser.setUserId("u" + CustomId.timestamp());
                wxUser.setShareNum(CustomId.randomWords(Integer.parseInt(
                        configService.selectConfigByKey("user.share.length"))));
                wxUser.setUserRegtime(new Date());
                wxUser.setOpenId(openId);
                wxUserService.insertWxUser(wxUser);
            }

            JSONObject token = new JSONObject();
            token.put("token", sessionKey);
            return AjaxResult.success(token);
        }
        return AjaxResult.error();
    }

    /**
     * 获取当前用的明细
     *
     * @return
     */
    @RequestMapping("/getInfo")
    public AjaxResult getInfo(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        WxUser user = wxUserService.selectWxUserByUserId(userId);
        if (user != null) {
            JSONObject json = new JSONObject();
            json.put("img", StringUtils.isBlank(user.getPic()) ? QiniuUtils.DOMAIN + "/mh/head/head.png" : QiniuUtils.DOMAIN + "/" + user.getPic());
            json.put("nickName", StringUtils.isBlank(user.getNickName()) ? "美禾记账" : user.getNickName());
            json.put("viewId", user.getViewId());
            json.put("shareId", user.getShareNum());
            return AjaxResult.success("获取用户信息成功!", json);
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 修改昵称
     */
    @RequestMapping("/update")
    public AjaxResult update(HttpServletRequest request, WxUser user) {
        String userId = (String) request.getAttribute("userId");
        user.setUserId(userId);
        wxUserService.updateWxUser(user);
        return AjaxResult.success("更新用户信息成功!");
    }
}
